package com.example.qrcode.controller;

import com.example.qrcode.vo.LoginVo;
import com.example.qrcode.vo.ResultVo;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


import com.example.qrcode.entity.User;
import com.example.qrcode.service.UserService;

import javax.annotation.Resource;


@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 登录接口 - 验证用户名和密码
     */
    @PostMapping
    public ResultVo<Map<String, Object>> login(@RequestBody LoginVo loginVo) {
        try {
            System.out.println("=== 登录请求 ===");
            System.out.println("用户名: " + loginVo.getUsername());
            System.out.println("密码: " + (loginVo.getPassword() != null ? "已提供" : "未提供"));

            // 1. 验证用户名是否存在
            User user = userService.findByUsername(loginVo.getUsername());
            if (user == null) {
                System.out.println("用户不存在: " + loginVo.getUsername());
                return ResultVo.error("用户名不存在");
            }

            // 2. 验证密码（实际项目中应该使用加密验证）
            if (!user.getPassword().equals(loginVo.getPassword())) {
                System.out.println("密码错误: " + loginVo.getUsername());
                return ResultVo.error("密码错误");
            }

            // 3. 登录成功，返回用户信息
            Map<String, Object> data = new HashMap<>();
            data.put("token", "token-" + System.currentTimeMillis() + "-" + user.getId());
            data.put("username", user.getUsername());
            data.put("role", user.getRole());
            data.put("nickName", user.getNickName());

            System.out.println("登录成功: " + user.getUsername() + ", 角色: " + user.getRole());
            return ResultVo.success(data);

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("登录异常: " + e.getMessage());
            return ResultVo.error("登录异常：" + e.getMessage());
        }
    }

    @GetMapping("/test")
    public ResultVo<String> test() {
        return ResultVo.success("测试接口  login");
    }
}

